package com.ce.server.config.security;

import com.ce.server.config.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * jwt授权过滤器
 *
 * @DATE: 2021/11/14 17:04
 * @Author: 小爽帅到拖网速
 */
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

  @Value("${jwt.tokenHeader}")
  private String tokenHeader;
  @Value("${jwt.tokenHead}")
  private String tokenHead;

  @Autowired
  private JwtTokenUtil jwtTokenUtil;
  @Autowired
  private UserDetailsService userDetailsService;


  // 前置拦截
  @Override
  protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

    String authHeader = request.getHeader(tokenHeader);
    if (authHeader != null && authHeader.startsWith(tokenHead)) {
      // 前端请求存在token
      String authToken = authHeader.substring(tokenHead.length());
      String no = jwtTokenUtil.getUserNameFromToken(authToken);


      // 查询到用户账号，但是未登录
      if (no != null && SecurityContextHolder.getContext().getAuthentication() == null) {

        UserDetails userDetails = userDetailsService.loadUserByUsername(no);
        // 验证token是否有效
        if (userDetails != null && jwtTokenUtil.validateToken(authToken, userDetails)) {
          // 有效则进行登录
          UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
          // 重新设置到用户对象中去
          authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
          SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
      }
    }
    filterChain.doFilter(request, response);
  }
}
